import requests,sys
from bs4 import BeautifulSoup
from multiprocessing.dummy import Pool
class downloader(object):
    def __init__(self):
        self.server = 'http://www.biqukan.com/'
        self.target = 'https://www.biqukan.com/3_3050/'
        self.names = []  # 存放章节名
        self.urls = []   # 存放章节链接
        self.nums = 0   # 章节数
    def get_download_url(self):
        req = requests.get(url=self.target)
        soup = BeautifulSoup(req.content, 'lxml', from_encoding='utf-8')
        div = soup.find_all('div', class_ = 'listmain')
        listmain = BeautifulSoup(str(div[0]), 'lxml')
        a=listmain.find_all('a')
        self.nums = len(a[500:])
        for each in a[500:]:
            self.names.append(each.string)
            self.urls.append(self.server + each.get('href'))
    def get_contents(self, target):
        req = requests.get(url=target)
        contents = BeautifulSoup(req.content, 'lxml')
        texts = contents.find_all('div', class_='showtxt')
        texts = texts[0].text.replace('\xa0' * 8, '\n\n').replace('\xa0' * 2, '')
        return texts
    def writer(self, name, path, text):
        with open(path, 'a', encoding='utf-8') as f:
            f.write(name + '\n')
            f.writelines(text)
            f.write('\n\n')
dl = downloader()
dl.get_download_url()

def downloadTxt(i):
    dl.writer(dl.names[i], '凡人修仙传.txt', dl.get_contents(dl.urls[i]))
    print(i)
    sys.stdout.write("  已下载:%.3f%%" % float(i / dl.nums * 100) + '\r')
    sys.stdout.flush()
def workMulti(i):
    return i
if __name__ == "__main__":
    print('《凡人修仙传》开始下载：')
    # lock = Lock()
    po = Pool(processes=8)  # 允许开几个线程/进程
    for i in range(dl.nums):
        po.apply_async(workMulti, args=(i,), callback=downloadTxt)
    po.close()
    po.join()